﻿using System;
using System.Messaging;
using System.Threading;

namespace CppUT
{
    namespace Common
    {
        public class MessageListener
        {
            public MessageListener(string aMessageQueueName)
            {
                _messageQueueName = aMessageQueueName;
            }

            public void Listen()
            {
                Log.MethodEntry();

                _listener = new Thread(ScanContinuous);
                _listener.Priority = ThreadPriority.BelowNormal;
                _listener.IsBackground = true;
                _listener.Start();

                Log.MethodExit();
            }

            public void Stop()
            {
                Log.MethodEntry();

                _listener.Abort();

                Log.MethodExit();
            }

            //  Run scan continuous as background task
            private void ScanContinuous()
            {
                //Log.MethodEntry();
                var messageQueue = new MessageQueue(_messageQueueName);
                if (null == messageQueue)
                {
                    throw new InvalidOperationException("Message queue unavailable.");
                }

                while (true)
                {
                    messageQueue.Refresh();
                    var message = messageQueue.Receive();
                    if (message != null)
                    {
                        MessageReceived(message);
                    }
                }
            }

            public delegate void TestMessageHandler(Message message);
            public event TestMessageHandler MessageReceived;
            private Thread _listener;
            private string _messageQueueName;
        }
    }
}